package economy;

import java.util.HashMap;

import org.bukkit.entity.Player;

public class Exchange {
	private static Exchange exchange = null;
	public static Exchange instance() {
		if (exchange == null) {
			exchange = new Exchange();
		}
		return exchange;
	}
	private HashMap<Integer, Item> items = new HashMap<Integer, Item>();

	private HashMap<String, Integer> ids = new HashMap<String, Integer>();;

	private Exchange() {
	}

	public void addItem(String name, int id, int baseValue, int supplyFactor,
			int profitFactor, int currentSupply) {
		items.put(id, new Item(name, id, baseValue, supplyFactor, profitFactor,
				currentSupply));
		ids.put(name, id);
	}

	public int checkBuyPrice(int id) {
		return items.get(id).buyPrice();
	}

	public int checkBuyPrice(String item) {
		return checkBuyPrice(ids.get(item));
	}

	public int checkSellPrice(int id) {
		return items.get(id).sellPrice();
	}

	public int checkSellPrice(String item) {
		return checkSellPrice(ids.get(item));
	}

	public boolean contains(String item) {
		return ids.containsKey(item);
	}

	public boolean sale(Player player, int id, int quantity) {
		Money money = (Money) player.getMetadata("money").get(0).value();
		Item item = items.get(id);
		if (quantity <= 0) {
			player.sendMessage("Invalid amount");
		} else if (quantity > item.currentSupply()) {
			player.sendMessage("Quantity requested exceeds current supply");
		} else if (money.amount() < item.sellPrice() * quantity) {
			player.sendMessage("You do not have enough money!");
		} else {
			money.subtract(item.sellPrice() * quantity);
			item.subtract(quantity);
			player.sendMessage("You have bought " + quantity + " "
					+ item.name());
			return true;
		}
		return false;
	}

	public boolean sale(Player player, String item, int quantity) {
		return this.sale(player, ids.get(item), quantity);
	}
}
